import { Application, codo } from "egg";
import WeWorkBaseService from "./WeWorkBaseService";

/**
 * 企业自建应用调用，认证授权相关
 */
export default class Auth extends WeWorkBaseService {
	constructor(
		protected config: codo.WeWork.IWeWorkConfig,
		private accessToken: string,
		protected app: Application
	) {
		super(config, app);
	}

	/** 自建应用
	 * -  获取用户信息，by 网页授权登录等场景下的code */
	async getUserInfoByCode(code: string) {
		const appAccessToken = this.accessToken;
		const url = `https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=${appAccessToken}&code=${code}`;

		const res = await this.curl<codo.WeWork.IAuthUserInfoResponse>(url, {
			method: "GET",
			dataType: "json",
			contentType: "json",
			timeout: [30000, 30000],
		});
		if (res.data.errcode === 0) {
			return res.data;
		} else {
			this.app.logger.error(`通过code获取用户信息异常 %j`, res.data);
			throw new Error(res.data.errcode + res.data.errmsg);
		}
	}
}
